# code:utf8
import json
import math
from pyquery import PyQuery
from datetime import datetime
from scrapy.utils.project import get_project_settings
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.pipelines.helper.supplier_helper import SupplierHelper
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.encrypt_util import short_uuid
from zc_core.model.items import Catalog, Supplier, Sku, ItemData, OrderItem, Brand, ItemGroup
from zc_core.util.common import parse_number, parse_time
from zc_core.util.order_deadline_filter import OrderItemFilter
from changsha.matcher import match_cat_id_from_js, match_supplier_id_from_link

order_filter = OrderItemFilter()


# 解析catalog列表
def parse_catalog(response):
    settings = get_project_settings()
    root_cats = settings.get('ROOT_CAT', {})

    jpy = PyQuery(response.text)
    cat1_links = jpy('div.banner-nav ul.c-nav li a')
    cat23_divs = jpy('div.banner-nav div.c-nav-boxs div.products-cate')

    cats = list()
    for idx, cat1_a in enumerate(cat1_links.items()):
        # goFirstType(2,1)
        # cat1_id = match_cat_id_from_js(cat1_a.attr('onclick'))
        cat1_name = cat1_a.text().strip()
        cat1_id = root_cats.get(cat1_name, 'ROOT_{}'.format(idx))
        cat1 = _build_catalog(cat1_id, cat1_name, '', 1)
        cats.append(cat1)

        dls = cat23_divs.eq(idx).children('dl')
        for dl in dls.items():
            cat2_a = dl('dt a')
            cat2_id = match_cat_id_from_js(cat2_a.attr('onclick'))
            cat2_name = cat2_a.text().strip()
            cat2 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat2)

            cat3_link = dl('dd a')
            for cat3_a in cat3_link.items():
                cat3_id = match_cat_id_from_js(cat3_a.attr('onclick'))
                cat3_name = cat3_a.text().strip()
                cat3 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                cats.append(cat3)

    return cats


def _build_catalog(cat1_id, cat1_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat1_id
    cat['catalogName'] = cat1_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 1

    return cat


# 解析brand列表
def parse_brand(response):
    meta = response.request.meta
    rs = json.loads(response.text)
    brands = list()
    for br in rs:
        brand = Brand()
        brand['id'] = br.get('id')
        brand['name'] = br.get('brand_name')
        brand['batchNo'] = meta.get('batchNo')
        brands.append(brand)

    return brands


# 解析supplier列表
def parse_supplier_page(response):
    jpy = PyQuery(response.text)
    count = int(jpy('h3 i.result-num').text().strip())
    if count > 0:
        return math.ceil(count / 5)

    return 0


# 解析supplier列表
def parse_supplier(response):
    jpy = PyQuery(response.text)
    sp_links = jpy('dd.shop-name a')

    suppliers = list()
    for sp_link in sp_links.items():
        supplier = Supplier()
        supplier['id'] = match_supplier_id_from_link(sp_link.attr('href'))
        supplier['name'] = sp_link.text().strip()
        suppliers.append(supplier)

    return suppliers


# 解析sku列表总页数
def parse_sku_pagination(response):
    jpy = PyQuery(response.text)
    total_page = jpy('i.totalPageCount').text()
    if total_page:
        return int(total_page.strip())

    return 0


# 解析ItemData
def parse_item_data(response):
    cat_helper = CatalogHelper()
    sp_helper = SupplierHelper()
    skus = list()
    items = list()

    meta = response.meta
    cat_id = meta.get('catalogId')
    sp_id = meta.get('supplierId')
    jpy = PyQuery(response.text)
    lis = jpy('ul.gl-wrap li')
    if lis:
        for li in lis.items():
            sku = Sku()
            item = ItemData()
            batch_no = meta.get('batchNo')
            sku_id = str(li.attr('id'))
            li('span.price font').remove()
            price_text = li('span.price').text()
            # -------------------------------------------------
            item['batchNo'] = batch_no
            sku['batchNo'] = batch_no
            item['skuId'] = sku_id
            sku['skuId'] = sku_id
            item['skuName'] = li('div.item-second a').attr('title').strip()
            item['catalog3Id'] = cat_id
            cat_helper.fill(item)
            item['salePrice'] = parse_number(price_text)
            sku['salePrice'] = parse_number(price_text)
            item['originPrice'] = item['salePrice']
            sp_name = sp_helper.get_name_by_id(sp_id)
            item['supplierId'] = sp_id
            sku['supplierId'] = sp_id
            item['supplierName'] = sp_name
            sku['supplierName'] = sp_name

            skus.append(sku)
            items.append(item)
            # -------------------------------------------------

    return skus, items


# 解析group关系
def parse_group(response):
    meta = response.request.meta
    rs = json.loads(response.text)
    spu_id = short_uuid()
    group = ItemGroup()
    if rs:
        ids = list()
        group['skuIdList'] = ids
        group['spuId'] = spu_id
        group['batchNo'] = meta.get('batchNo')
        group['skuId'] = meta.get('skuId')
        for idx, row in enumerate(rs):
            if idx > 0:
                sku_id = str(row.get('productid'))
                ids.append(sku_id)

    return group


# 解析sku列表
def parse_order_item(response):
    rs = json.loads(response.text)
    meta = response.meta
    sp_id = meta.get('supplierId')
    sku_id = meta.get('skuId')

    orders = list()
    rs_list = rs.get('ordersList')
    if len(rs_list):
        for row in rs_list:
            order_time = _calc_order_time(row.get('ordersno'))
            if order_filter.to_save(order_time):
                order = OrderItem()
                order['id'] = row.get('ordersno')
                order['orderId'] = row.get('totalordersno')
                order['skuId'] = sku_id
                order['count'] = row.get('count')
                order['amount'] = row.get('allMoney')
                order['tradeType'] = row.get('type')
                order['orderDept'] = row.get('agencyname')
                order['supplierId'] = str(sp_id)
                order['orderTime'] = order_time
                order['batchNo'] = time_to_batch_no(order_time)
                order['genTime'] = datetime.utcnow()
                orders.append(order)

    return orders


# 根据订单编号解析采购时间
def _calc_order_time(order_id):
    if order_id and len(order_id) >= 14:
        return parse_time(order_id[:14], fmt='%Y%m%d%H%M%S')
    return ''


# # 测试
if __name__ == '__main__':
    print(_calc_order_time('2018111916294479'))
